<html>
  <head>
    <meta charset="utf-8">
  </head>
  <body>
    <h1>OrbitDB - Benchmark log.add()</h1>

    <h2>Description</h2>
    <div>Add an entry to a log database. Measure throughput in write operations per second.</div>

    <h2>Results</h2>
    <pre id="output"></pre>

    <script type="text/javascript" src="../../dist/orbitdb.min.js" charset="utf-8"></script>
    <script type="text/javascript" src="../../node_modules/ipfs/dist/index.js" charset="utf-8"></script>

    <script type="text/javascript">
      let ipfs

      // Metrics
      let totalQueries = 0
      let seconds = 0
      let queriesPerSecond = 0
      let lastTenSeconds = 0

      const queryLoop = async (db) => {
        await db.add(totalQueries)
        totalQueries ++
        lastTenSeconds ++
        queriesPerSecond ++
        setImmediate(() => queryLoop(db))
      }

      let run = (() => {
        ipfs = new Ipfs({
          repo: '/orbitdb/benchmarks/browser/benchmark-add/0.27.0',
          start: false,
          EXPERIMENTAL: {
            pubsub: true,
            sharding: false,
            dht: false,
          },
        })

        ipfs.on('error', (err) => console.error(err))

        ipfs.on('ready', async () => {
          const outputElm = document.getElementById('output')
          try {
            const orbit = await OrbitDB.createInstance(ipfs, { directory: './orbitdb/benchmarks/browser' })
            const db = await orbit.eventlog('orbit-db.benchmark.add', {
              replicate: false,
            })

            // Metrics output
            setInterval(() => {
              seconds ++
              if(seconds % 10 === 0) {
                outputElm.innerHTML = `--> Average of ${lastTenSeconds/10} q/s in the last 10 seconds<br>` + outputElm.innerHTML
                console.log(`--> Average of ${lastTenSeconds/10} q/s in the last 10 seconds`)
                if(lastTenSeconds === 0)
                  throw new Error("Problems!")
                lastTenSeconds = 0
              }
              outputElm.innerHTML = `${queriesPerSecond} queries per second, ${totalQueries} queries in ${seconds} seconds (Entries: ${db._oplog.length})<br>` + outputElm.innerHTML
              // console.log(`${queriesPerSecond} queries per second, ${totalQueries} queries in ${seconds} seconds (Entries: ${db._oplog.length})`)
              queriesPerSecond = 0
            }, 1000)
            // Start the main loop
            queryLoop(db)
          } catch (e) {
            console.error(e)
          }
        })
      })()
    </script>
  </body>
</html>
